package com.ms.module.wechat.clear.fragment.clear;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.entity.node.BaseNode;
import com.ms.module.wechat.clear.R;
import com.ms.module.wechat.clear.base.BaseFragment;
import com.ms.module.wechat.clear.base.RxView;
import com.ms.module.wechat.clear.fragment.adapter.node.FileHeaderNode;
import com.ms.module.wechat.clear.fragment.adapter.node.UpChildNode;
import com.ms.module.wechat.clear.fragment.adapter.node.UpGroupNode;
import com.ms.module.wechat.clear.internal.WeChatClearCommonn;
import com.ms.module.wechat.clear.repository.SharedPreferencesData;
import com.ms.module.wechat.clear.repository.WeChatScanDataRepository;
import com.ms.module.wechat.clear.utils.ByteSizeToStringUnitUtils;
import com.ms.module.wechat.clear.utils.ListDataUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.RandomAccess;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ClearFragment extends BaseFragment implements RxView.Action1<View> {

    private static final String TAG = "ClearFragment";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_wechat_clear_finsh;
    }

    private static ClearFragment instance;
    private RecyclerView recyclerView;
    private Adapter adapter;
    private List<BaseNode> datas = new ArrayList<>();
    private ClearFragmentViewModel viewModel;
    private TextView textViewTotalScanGarbageSize;
    private TextView textViewClear;
    private TextView textViewSizeUnit;
    private Observer<List<BaseNode>> observerDatas;
    private ImageView imageViewBack;
    private Long length;

    public static ClearFragment getInstance() {
        return instance;
    }

    public void updateNowClear() {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                boolean check = ListDataUtils.checkClearUpAllNode(datas);
                emitter.onNext(check);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<Boolean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull Boolean check) {

                        Log.e(TAG, "onNext: " + check);
                        if (check) {
                            textViewClear.setEnabled(true);
                            textViewClear.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_blue));
                        } else {
                            textViewClear.setEnabled(false);
                            textViewClear.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_gray));
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });

        Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Long> emitter) throws Exception {
                //long nowClearFilesLength = WeChatScanDataRepository.getInstance().getNowClearFilesLength(datas);
                long nowClearFilesLength = 0;

                for (int i = 0; i < datas.size(); i++) {
                    BaseNode baseNode = datas.get(i);
                    if (baseNode instanceof UpGroupNode) {
                        UpGroupNode upGroupNode = (UpGroupNode) baseNode;
                        List<BaseNode> childNode = upGroupNode.getChildNode();
                        for (int j = 0; j < childNode.size(); j++) {
                            BaseNode baseNode1 = childNode.get(j);
                            if (baseNode1 instanceof UpChildNode) {
                                UpChildNode upChildNode = (UpChildNode) baseNode1;
                                if (upChildNode.isCheck()) {
                                    nowClearFilesLength += upChildNode.getSize();
                                }
                            }
                        }
                    }
                }
                emitter.onNext(nowClearFilesLength);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull Long nowClearFilesLength) {
                        if (nowClearFilesLength == 0) {
                            textViewClear.setEnabled(false);
                            textViewClear.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_gray));
                            textViewClear.setText("立即清理");
                        } else {
                            textViewClear.setEnabled(true);
                            textViewClear.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_blue));
                            textViewClear.setText("立即清理 " + ByteSizeToStringUnitUtils.byteToStringUnit(+nowClearFilesLength));
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


        Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Long> emitter) throws Exception {
                length = WeChatScanDataRepository.getInstance().getMutableLiveDataTotalScanGarbageSize().getValue();
                if (length == null) {
                    length = new Long(0);
                }

                for (int i = 0; i < datas.size(); i++) {
                    BaseNode baseNode = datas.get(i);
                    if (baseNode instanceof UpGroupNode) {
                        UpGroupNode upGroupNode = (UpGroupNode) baseNode;
                        List<BaseNode> childNode = upGroupNode.getChildNode();
                        for (int j = 0; j < childNode.size(); j++) {
                            BaseNode baseNode1 = childNode.get(j);

                            if (baseNode1 instanceof UpChildNode) {
                                UpChildNode upChildNode = (UpChildNode) baseNode1;

                                if (upChildNode.isCheck()) {
                                    length += upChildNode.getSize();
                                }
                            }
                        }
                    }
                }

                emitter.onNext(length);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Long length) {
                        String[] res = ByteSizeToStringUnitUtils.byteToStringUnitS(length);
                        textViewTotalScanGarbageSize.setText(res[0]);
                        textViewSizeUnit.setText(res[1] + "\n可清理");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    @Override
    protected void initView() {
        super.initView();
        recyclerView = findViewById(R.id.recyclerView);
        textViewTotalScanGarbageSize = findViewById(R.id.textViewTotalScanGarbageSize);
        textViewClear = findViewById(R.id.textViewClear);
        textViewSizeUnit = findViewById(R.id.textViewSizeUnit);
        imageViewBack = findViewById(R.id.imageViewBack);
        RxView.setOnClickListeners(this::onClick, textViewClear, imageViewBack);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        instance = this;

        viewModel = new ViewModelProvider(this).get(ClearFragmentViewModel.class);
        try {
            if (WeChatScanDataRepository.getInstance().getMutableLiveDataTotalScanGarbageSize() != null) {
                length = WeChatScanDataRepository.getInstance().getMutableLiveDataTotalScanGarbageSize().getValue();
                if (length == null) {
                    length = new Long(0);
                }
                // 扫描完成
                WeChatClearCommonn.getWeChatClearCallBack().onScanFinish(getActivity(), Lifecycle.Event.ON_CREATE, length);
                String[] res = ByteSizeToStringUnitUtils.byteToStringUnitS(length);
                textViewTotalScanGarbageSize.setText(res[0]);
                textViewSizeUnit.setText(res[1] + "\n可清理");
            } else {
                // 扫描完成
                WeChatClearCommonn.getWeChatClearCallBack().onScanFinish(getActivity(), Lifecycle.Event.ON_CREATE, 0);
            }
            textViewClear.setText("立即清理");
        } catch (Exception e) {
            e.printStackTrace();
        }

        adapter = new Adapter();
        adapter.setList(datas);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter.notifyDataSetChanged();

        observerDatas = new Observer<List<BaseNode>>() {
            @Override
            public void onChanged(List<BaseNode> baseNodes) {
                datas.clear();
                datas.addAll(baseNodes);
                adapter.setList(datas);
                adapter.notifyDataSetChanged();
                updateNowClear();
            }
        };

        viewModel.getLiveDataDatas().observe(getViewLifecycleOwner(), observerDatas);
        viewModel.getMutableLiveDataDatas().postValue(null);
    }


    @Override
    public void onClick(View view) {
        // 立即清理
        if (view.getId() == R.id.textViewClear) {

            Observable.create(new ObservableOnSubscribe<Long>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<Long> emitter) throws Exception {

                    // 计算删除文件的大小
                    long filesLength = WeChatScanDataRepository.getInstance().getFilesLength(datas);

                    if (filesLength == 0) {
                        for (int i = 0; i < datas.size(); i++) {
                            BaseNode baseNode = datas.get(i);
                            if (baseNode instanceof UpGroupNode) {
                                UpGroupNode upGroupNode = (UpGroupNode) baseNode;
                                List<BaseNode> childNode = upGroupNode.getChildNode();
                                for (int j = 0; j < childNode.size(); j++) {
                                    BaseNode baseNode1 = childNode.get(j);
                                    if (baseNode1 instanceof UpChildNode) {
                                        UpChildNode upChildNode = (UpChildNode) baseNode1;
                                        if (upChildNode.isCheck()) {
                                            filesLength += upChildNode.getSize();
                                        }
                                    }
                                }
                            }
                        }

                        Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                                for (int i = 0; i < datas.size(); i++) {
                                    BaseNode baseNode = datas.get(i);
                                    if (baseNode instanceof UpGroupNode) {
                                        UpGroupNode upGroupNode = (UpGroupNode) baseNode;
                                        List<BaseNode> childNode = upGroupNode.getChildNode();
                                        for (int j = 0; j < childNode.size(); j++) {
                                            BaseNode baseNode1 = childNode.get(j);
                                            if (baseNode1 instanceof UpChildNode) {
                                                UpChildNode upChildNode = (UpChildNode) baseNode1;


                                                if (upChildNode.isCheck()) {
                                                    upGroupNode.setSize(upGroupNode.getSize() - upChildNode.getSize());
                                                    upChildNode.setSize(0);
                                                }

                                            }
                                        }
                                    }
                                }
                                emitter.onNext(true);
                            }
                        }).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new io.reactivex.Observer<Boolean>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {
                                    }

                                    @Override
                                    public void onNext(@NonNull Boolean aBoolean) {
                                        if (adapter != null) {
                                            adapter.setList(datas);
                                            adapter.notifyDataSetChanged();
                                            updateNowClear();
                                        }
                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                    }

                                    @Override
                                    public void onComplete() {
                                    }
                                });

                        emitter.onNext(filesLength);

                    } else {
                        WeChatScanDataRepository.getInstance().deleteFile(datas, new io.reactivex.Observer<Boolean>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {
                            }

                            @Override
                            public void onNext(@NonNull Boolean aBoolean) {
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                                if (adapter != null) {
                                    adapter.setList(datas);
                                    adapter.notifyDataSetChanged();
                                    updateNowClear();
                                }
                            }
                        });
                        emitter.onNext(filesLength);
                    }

                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<Long>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                        }

                        @Override
                        public void onNext(@NonNull Long filesLength) {
                            // 立即清理回调
                            WeChatClearCommonn.getWeChatClearCallBack().onClearUpNow(getActivity(), filesLength.longValue());
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else if (view.getId() == R.id.imageViewBack) {
            // 返回按钮，关闭微信清理模块
            getActivity().finish();
            WeChatClearCommonn.getWeChatClearCallBack().onClose(getActivity());
        }
    }
}
